package com.example.controller;

import com.example.dao.DepartmentDAO;
import com.example.model.Department;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "DepartmentServlet", value = {
        "/departments", "/addDepartment", "/editDepartment", "/updateDepartment", "/deleteDepartment"
})
public class DepartmentServlet extends HttpServlet {
    private DepartmentDAO departmentDAO;
    private static final int RECORDS_PER_PAGE = 5;

    @Override
    public void init() {
        departmentDAO = new DepartmentDAO();
    }
    private boolean isAdmin(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        return session != null && "admin".equals(session.getAttribute("role"));
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (!isAdmin(request)) {
            response.sendRedirect("login.jsp");
            return;
        }
        String action = request.getServletPath();

        if ("/addDepartment".equals(action)) {
            addDepartment(request, response);
        } else if ("/updateDepartment".equals(action)) {
            updateDepartment(request, response);
        } else if ("/deleteDepartment".equals(action)) {
            deleteDepartment(request, response);
        } else {
            response.sendRedirect("departments");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (!isAdmin(request)) {
            response.sendRedirect("login.jsp");
            return;
        }
        String action = request.getServletPath();

        if ("/departments".equals(action)) {
            listDepartments(request, response);
        } else if ("/addDepartment".equals(action)) {
            showAddForm(request, response);
        } else if ("/editDepartment".equals(action)) {
            showEditForm(request, response);
        } else if ("/deleteDepartment".equals(action)) {
            deleteDepartment(request, response);
        } else {
            response.sendRedirect("departments");
        }
    }

    private void listDepartments(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取当前页码，默认为第一页
            int page = 1;
            String pageParam = request.getParameter("page");
            if (pageParam != null && !pageParam.isEmpty()) {
                page = Integer.parseInt(pageParam);
            }

            // 获取部门总数
            int totalDepartments = departmentDAO.getTotalDepartments();
            int totalPages = (int) Math.ceil((double) totalDepartments / RECORDS_PER_PAGE);

            // 设置请求属性
            request.setAttribute("departments", departmentDAO.getAllDepartments());
            request.setAttribute("currentPage", page);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("totalDepartments", totalDepartments);

            // 转发到列表页面
            RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/listDepartments.jsp");
            dispatcher.forward(request, response);
        } catch (Exception e) {
            throw new ServletException("Error listing departments", e);
        }
    }

    private void showAddForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/addDepartment.jsp");
        dispatcher.forward(request, response);
    }

    private void addDepartment(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Department dept = new Department();
        dept.setDeptName(request.getParameter("deptName"));
        dept.setManager(request.getParameter("manager"));
        dept.setLocation(request.getParameter("location"));

        try {
            departmentDAO.addDepartment(dept);
            // 添加成功后重定向到部门列表
            response.sendRedirect("departments");
        } catch (Exception e) {
            throw new ServletException("Error adding department", e);
        }
    }
    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            int deptId = Integer.parseInt(request.getParameter("id"));
            Department department = departmentDAO.getDepartmentById(deptId);

            if (department != null) {
                request.setAttribute("department", department);
                RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/editDepartment.jsp");
                dispatcher.forward(request, response);
            } else {
                response.sendRedirect("departments");
            }
        } catch (Exception e) {
            throw new ServletException("Error showing edit form", e);
        }
    }

    private void updateDepartment(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Department dept = new Department();
        dept.setDeptId(Integer.parseInt(request.getParameter("id")));
        dept.setDeptName(request.getParameter("deptName"));
        dept.setManager(request.getParameter("manager"));
        dept.setLocation(request.getParameter("location"));

        try {
            departmentDAO.updateDepartment(dept);
            response.sendRedirect("departments");
        } catch (Exception e) {
            throw new ServletException("Error updating department", e);
        }
    }

    private void deleteDepartment(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int deptId = Integer.parseInt(request.getParameter("id"));
        try {
            departmentDAO.deleteDepartment(deptId);
            response.sendRedirect("departments");
        } catch (Exception e) {
            throw new ServletException("Error deleting department", e);
        }
    }

}
